package com.example.canteen.service;

import com.example.canteen.converter.CategoryConverter;
import com.example.canteen.converter.DishConverter;
import com.example.canteen.dao.Category;
import com.example.canteen.dao.CategoryRepository;
import com.example.canteen.dto.CategoryDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Set;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryRepository categoryRepository;

    @Override
    public Set<CategoryDTO> getAllCategories() {
        return categoryRepository.findAll().stream().map(CategoryConverter::convertCategory).collect(Collectors.toSet());
    }

    @Transactional
    @Override
    public void deleteCategoryByName(String name) {
        categoryRepository.deleteByName(name);
    }


    @Override
    public Long addCategory(CategoryDTO categoryDTO) {
        if (categoryRepository.findByName(categoryDTO.getName()) != null) {
            throw new IllegalArgumentException("Category already exists");
        }
        return categoryRepository.save(CategoryConverter.convertCategory(categoryDTO)).getId();
    }

    @Override
    public CategoryDTO updateCategory(long id, String name) {
        Category categoryInDB = categoryRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Category not found"));
        if (StringUtils.hasLength(name) && !name.equals(categoryInDB.getName())) {
            categoryInDB.setName(name);
        }
        return CategoryConverter.convertCategory(categoryRepository.save(categoryInDB));
    }
}
